<!-- by 752718920 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('financialManagement.lessee')" :labelCol="labelCol"
                    :wrapperCol="wrapperCol">
                    <a-select :placeholder="$t('basicInformation.pleaseSelect')+$t('financialManagement.lessee')" v-model="queryParam.tenantId">
                      <a-select-option :value="item.tenantId" v-for="(item,index) in tenantList" :key="index">{{ item.loginName || '-' }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('manuManagement.documentDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                    style="width:100%"
                    v-model="queryParam.createTimeRange"
                    format="YYYY-MM-DD"
                    :placeholder="[$t('manuManagement.startTime'), $t('manuManagement.endTime')]"
                    @change="onDateChange"
                    @ok="onDateOk"
                    :allowClear="false"
                  />
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="6" :sm="24">
                  <a-button type="primary" @click="searchQuery">{{$t('manuManagement.query')}}</a-button>
                  <!-- <a-button style="margin-left: 8px" @click="searchReset">{{$t('manuManagement.reset')}}</a-button> -->
                </a-col>
              </span>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator"  style="margin-top: 5px">
          <ColumnsSetting style="ma" @columnsChange="columnsChange" :columns="columns"></ColumnsSetting>
          <a-tooltip placement="left" :title="$t('financialManagement.theEtc')" slot="action">
            <a-icon v-if="btnEnableList.indexOf(1)>-1" type="question-circle" style="font-size:20px;float:right;" />
          </a-tooltip>
          <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="print" icon="printer">{{$t('reportQuery.print')}}</a-button>
          <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button>
          <a-button v-if="btnEnableList.indexOf(3) > -1" :loading="downLoading" style="margin-left: 8px" @click="exportExcel" icon="download">{{$t('reportQuery.export')}}</a-button>        
          <a-button type="primary"  style="margin-left: 8px" @click="handleDetail" icon="bar-chart">{{$t('otherJS.officeClerkSummary')}}</a-button>      
          </div>
        <!-- table区域-begin -->
        <section ref="print" id="reportPrint">
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :customRow="rowClick"
            :loading="loading">
          </a-table>
        </section>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <SalesCollectReportModual ref="salesCollectReportModual"></SalesCollectReportModual>
        <financial-detail ref="modalDetail"></financial-detail>
      </a-card>
    </a-col>
    <saleOutRepotModual ref="saleOutRepotModual" :list="dataSource" :columns="columns" :queryParam="queryParam"></saleOutRepotModual>
  </a-row>
</template>
<script>
  import SalesCollectReportModual from './modules/SalesCollectReportModual'
  import FinancialDetail from '@/views/financial/dialog/FinancialDetail'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { FinancialListMixin } from '@/views/financial/mixins/FinancialListMixin'
  import {getAction} from '@/api/manage'
  import JDate from '@/components/jeecg/JDate'
  import { USER_INFO } from '@/store/mutation-types'
  import { filterObj } from '@/utils/util'
  import {getUserListByTenantId} from '@/api/api';
  import saleOutRepotModual from './modules/saleOutRepotModual';
  import moment from 'moment';
  import Vue from 'vue'
  export default {
    name: "DirectAdvanceReceiveList",
    mixins:[JeecgListMixin, FinancialListMixin],
    components: {
      SalesCollectReportModual,
      saleOutRepotModual,
      FinancialDetail,
      JDate,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        // 查询条件
        queryParam: {
          beginTime:'',
          endTime:'',
          tenantId:'',
          roleType: Vue.ls.get('roleType')
        },
        queryParamDetail:{
          beginTime:'',
          endTime:'',
          creator:'',
          roleType: Vue.ls.get('roleType')
        },

        userList:[],
        mainData:{},
        // 表头
        columns:[],
        totalColumns: [
          {
            title: this.$t('defaultTranslate.lineNumber'), dataIndex: 'rowIndex', width:40, align:"center",
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          }, 
          {title:this.$t('reportQuery.detail'), dataIndex: 'detail', width: 80,
            customRender:function (t,r,index) {
                return t || 'CASH SALES'
            }
          },
          {title:this.$t('manuManagement.customer'), dataIndex: 'organName', width: 80},
          {
            title: this.$t('manuManagement.documentNo'), dataIndex: 'number', width: 80,
            customRender: function (text, record, index) {
              if (record.linkNumber) {
                return text + "[订]";
              } else {
                return text;
              }
            }
          },
          {title:this.$t('otherJS.saleAmount'), dataIndex: 'discountLastMoney', sorter: (a, b) => a.operNumber - b.operNumber, width: 60,
            customRender:(t,r,index)=>{
                return this.$sinceCount(t)
            }},
          {title:this.$t('purchasingManagement.discountamount'), width: 60, dataIndex: 'discount',
            customRender:(t,r,index)=>{
                return this.$sinceCount(t)
            }},
          {title:this.$t('reportQuery.returnAmount'), width: 60, dataIndex: 'refunds',
            customRender:(t,r,index)=>{
                return this.$sinceCount(t)
            }},
          {title:this.$t('otherJS.salesTotal'), width: 60, dataIndex: 'allPrice',
            customRender:(t,r,index)=>{
                return this.$sinceCount(t)
            }},
        ],
        userColumns:[
          {title:this.$t('manuManagement.customer'),align:"left", dataIndex: 'organName',width:50},
          {title:this.$t('purchasingManagement.amount'),align:"center", dataIndex: 'amount',width:50,
            customRender:(t,r,index)=>{
                return this.$sinceCount(t)
            }},
        ],
        validatorRules:{
          tenantId:{
            rules: [
              { required: true, message: this.$t('systemManagement.pleaseTenant')+'!' }
            ]
          },
        },
        url: {
          list: "/depotHead/getDailySales",
          delete: "",
          deleteBatch: "",
          deApprovalUrl:'',
          batchSetStatusUrl: ""
        }
      }
    },
    computed: {
    },
    created () {
      let dateString = [moment(this.currentDay, this.dateFormat), moment(this.currentDay, this.dateFormat)]
      this.$set(this.queryParamDetail,'createTimeRange',dateString)
      this.initOrgan()
      this.initPerson()
      this.initAccount()
      this.initCustomer()
      this.getUserListByTenantId().then(()=>{
        this.$set(this.queryParamDetail,'creator',this.userList[0].id)
      })
      this.getTenant()
      this.columns = this.totalColumns
    },
    methods: {
      
    rowClick(record, index) {
      return {
        on: {
          click: () => {
          },
          dblclick: () => {
            console.log('双击了我')
            // this.myHandleDetail(record, '返利收款')
          },
        }
      }
    },
    getTenant(){
      return new Promise((resolve, reject) => {
        this.getTenantList().then(()=>{
          if(this.tenantList.length){
            this.$set(this.queryParam,'tenantId',this.tenantList[0] && this.tenantList[0].tenantId)
          }
          resolve()
        })
      })
    },
    onDateDetailChange: function (value, dateString) {
      console.log('dateString :>> ', dateString);
      this.queryParamDetail.beginTime = dateString[0]
      this.queryParamDetail.endTime = dateString[1]
    },
    getQueryParamsDetail () {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let searchObj = {}
      searchObj.search = JSON.stringify(this.queryParamDetail)
      var param = Object.assign(sqp, searchObj, this.isorter, this.filters)
      this.queryParamDetail.beginTime = this.currentDay
      this.queryParamDetail.endTime = this.currentDay
      param.field = this.getQueryField()
      // param.promotionType = this.promotionType
      param.currentPage = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    /**
     * 获取租户的职员
     */
    getUserListByTenantId(){
      return new Promise((resolve, reject) => {
        let userInfo = Vue.ls.get(USER_INFO)
        let param ={
          tenantId:userInfo.tenantId
        }
        getUserListByTenantId(param).then(res=>{
          this.userList = res || []
          resolve()
        })
      })
    },
    loadDetailData (arg) {
      console.log(this.url.list, this.title, 'handler: loadData')
      if (!this.url.list) {
        this.$message.error(this.$t('popup.pleaseProperty'))
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let param = this.getQueryParamsDetail()
      getAction(this.url.list, param).then(res => {
        this.loading = false
        if (res.code === 200) {
          let dataSource = res.data.rows || []
          let totalArray = []
          const generateDataSource = (obj)=>{
                  totalArray.push(obj)
          }
          
          // Cashier Report 零售
          totalArray.push({
            organName:`Cashier Report :   ` + this.getLocalStorage('pro__Login_Userinfo').loginName,
            
          })
          // 零售明细
          let retails = dataSource.filter(v=>v.organType === 1).map(v=>(v.organName = v.organName +' - CASH SALE',v))
          totalArray.push(...retails)
          // 零售汇总
          totalArray.push({
            organName:'Sub Total- Cash Customer',
            amount: retails.reduce((total,cur)=>{this.$toDecimal(total+cur.amount)},0)
          })
          // 普通客户汇总
          
          // 零售明细
          let normals = dataSource.filter(v=>v.organType === 2).map(v=>(v.organName = v.organName +' - CASH SALE',v))
          totalArray.push(...normals)
          // 零售汇总
          totalArray.push({
            organName:'Sub Total- Cash Account Customer',
            amount: normals.reduce((total,cur)=>{this.$toDecimal(total+cur.amount)},0)
          })
          this.dataSource = totalArray
          
              // 处理默认card高度不足
              this.$nextTick(()=>{
                setTimeout(()=>{
                  this.cardStyle = 'height:' + (document.body.scrollHeight - 125) + 'px'
                }, 1000);
              })
        }else{
          this.$message.error(res.msg || res.data)
        }
      })
    },
    handleDetail(){
      let item = this.tenantList.find(v=>v.tenantId === this.queryParam.tenantId)
      this.$refs.salesCollectReportModual.show(this.queryParam,this.btnEnableList,this.userList,item)
    },
    // 获取localStorage数据
    getLocalStorage (key) {
      var value = localStorage.getItem(key) // 取回 value 变量
      this.localStorageKeyJson = JSON.parse(value)
      return this.localStorageKeyJson.value
    },
    /**
     * 
     * @param {number} arg 查询第几页
     */
    async loadData (arg) {
      console.log('777 :>> ', 777);
      console.log(this.url.list, this.title, 'handler: loadData')
      if (!this.url.list) {
        this.$message.error(this.$t('popup.pleaseProperty'))
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      if(!this.queryParam.tenantId){
        await this.getTenant()
      }
      
      var params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params).then(res => {
        if (res.code === 200) {
          this.dataSource = (res.data.rows || []).map(v=>(v.detail = 'CASH SALES',v))
          this.mainData = res.data
          this.ipagination.total = res.data.total
          // this.innerColumns = 
          // if(!this.dataSource.length){this.loading = false;return};
          // 处理其他统计
          const strArr =[
            {title:'TOTAL CASH SALES',fun:(key)=>this.tableAddTotalRow(key)},
            {title:'CREDIT PAYMENTS',fun:(key)=>this.getPayMents(key),mult:true},
            {title:'TOTAL RECEIPTS',fun:(key)=>this.getReceipts(key)},
            {title:'CREDIT INVOICES',fun:()=>{},mult:true},
            {title:'GRAND TOTAL',fun:()=>{}},
          ]
          let totalArray = []
          /**
           * 
           * @param {array} arr 已经生成的dataSource
           * @param {string} columnKey 列key值
           * @param {string} str 筛选条件
           */
          const getTotalPayment = (arr,columnKey,str)=>{
              return arr.filter(v=>str.indexOf(v.detail) > -1).reduce((total,item)=>{return this.$toDecimal(total + +item[columnKey])},0)
          }
          const generateDataSource = (title,str)=>{
                  let parseCols ='discountLastMoney,discount,refunds,allPrice'
                  let creditObj = {}
                  parseCols.split(',').forEach(v=>{
                    creditObj[v] =  getTotalPayment(totalArray,v,str)
                  })
                  creditObj.detail = title
                  totalArray.push(creditObj)
          }
          for (let i = 0; i < strArr.length; i++) {
            if(i===0){
              let item = strArr[i]
              let obj = {}
              obj.detail = item.title
              this.columns.forEach(v=>{
                if(!('rowIndex,detail'.includes(v.dataIndex))){
                  obj[v.dataIndex] = item.fun(v.dataIndex)
                }
              })
              totalArray.push(obj)
            }else{
              // CREDIT PAYMENTS
              if(i==1){
                let creditPayment = this.mainData.creditPayment
                if(creditPayment && creditPayment.length){
                    let sinceArr = []
                    creditPayment.forEach(v=>{
                    totalArray.push({detail:'CREDIT PAYMENTS',discountLastMoney:0,discount:0,refunds:0,allPrice:0})
                    totalArray.push({
                      detail:'H_',
                      organName:v.supplier,
                      number:v.billNo,
                      discountLastMoney:v.changeAmount,
                      discount:0,
                      refunds:0,
                      allPrice:0
                    })
                  })
                  
                  // TOTAL CREDIT PAYMENT
                  let paymentRow = {detail:'H_',organName:'',number:'',discountLastMoney:0,discount:0,refunds:0,allPrice:0}
                  for (let key in paymentRow) { 
                    let parseCols ='discountLastMoney,discount,refunds,allPrice'
                    if(parseCols.indexOf(key) > -1){
                      paymentRow[key] = getTotalPayment(totalArray,key,'H_')
                    }else{
                      paymentRow[key] = ''
                    }
                  }
                  paymentRow.detail = 'TOTAL CREDIT PAYMENT'
                  totalArray.push(paymentRow)
                }
              }else if(i==3){
              // CREDIT INVOICES
                let creditInvoices = this.mainData.creditInvoices
                if(creditInvoices && creditInvoices.length){
                  totalArray.push({detail:'CREDIT INVOICES',discountLastMoney:0,discount:0,refunds:0,allPrice:0})
                  let sinceArr = []
                  creditInvoices.forEach(v=>{
                    let newObj ={}
                    for (let key in v) {
                      newObj[key] = v[key]
                    }
                    newObj.detail = 'CREDIT CUST'
                    sinceArr.push(newObj)
                  })
                  totalArray.push(...sinceArr)
                  // TOTAL CREDIT SALES
                  generateDataSource('TOTAL CREDIT SALES','CREDIT CUST')
                  // GRAND TOTAL
                  generateDataSource('GRAND TOTAL','TOTAL CREDIT SALES,TOTAL CASH SALES')
                }
              }else if(i == 2){
                // TOTAL RECEIPTS
                generateDataSource('TOTAL RECEIPTS','TOTAL CASH SALES,TOTAL CREDIT PAYMENT')
              }
            }
          }
          this.dataSource.push(...totalArray)
          this.ipagination.pageSize =this.dataSource.length
          
              // 处理默认card高度不足
              this.$nextTick(()=>{
                setTimeout(()=>{
                  this.cardStyle = 'height:' + (document.body.scrollHeight - 125) + 'px'
                }, 1000);
              })
        }
        if (res.code === 510) {
          this.$message.warning(res.data)
        }
        this.loading = false
      })
    },
    getPayMents(columnKey){
      return this.getBlankRow(columnKey)
    },
    getBlankRow(columnKey){
      let parseCols ='discountLastMoney,discount,refunds,allPrice'
      if(parseCols.indexOf(columnKey) > -1){
        return 0
      }
      return ''
    },

    /** 表格增加合计行 */
    tableAddTotalRow (columnKey) {
        let parseCols ='discountLastMoney,discount,refunds,allPrice'
        let t = ''
        if(parseCols.indexOf(columnKey) > -1){
          t = this.dataSource.reduce((total,item)=> { return total + item[columnKey]},0)
          return t.toFixed(2)
        }
       return t
    },
    // 获取未支付金额
    getReceipts(columnKey){
      let parseCols ='discountLastMoney,discount,refunds,allPrice'
      let num = columnKey === 'discountLastMoney' ? (this.mainData.totalCreditPayment || 0) : (parseCols.indexOf(columnKey) > -1 && 0)
      console.log('num :>> ', num);
      console.log('columnKey :>> ', columnKey);
      return num
    },
    getUserParam(){
      
    },
    getDailySalesDetail(){
      
      getDailySalesDetail().then(res=>{

      })
    },
    tabsChange(e){
      switch (e){
        case '1':
          this.$set(this.url,'list','/depotHead/getDailySales')
          this.loadData(1)
          break;
        case '2':
          this.$set(this.url,'list','/depotHead/getDailySalesDetail')
          this.loadDetailData(1)
          break;
        default:
          break;
      }
    },
    
    print(){
      this.$refs.saleOutRepotModual.show()
    }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>